package com.wmh.baseservice.operationaid.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wmh.baseservice.operationaid.mapper.CategoryMapper;
import com.wmh.baseservice.operationaid.entity.Category;
import com.wmh.baseservice.operationaid.pojo.vo.category.CategoryReqVO;
import com.wmh.baseservice.operationaid.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 谢骏
 * @description 针对表【operation_aid_category(运营助手-商品类目分类)】的数据库操作Service实现
 * @createDate 2023-05-26 16:39:24
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
        implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;


    @Override
    public void add(CategoryReqVO categoryReqVO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryReqVO, category);
        categoryMapper.insert(category);
    }

    @Override
    public List<Category> getList() {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        List<Category> allCategories = categoryMapper.selectList(queryWrapper);
        List<Category> level1Categories = allCategories.stream()
                .filter(category -> category.getParentId() == 1)
                .collect(Collectors.toList());

        List<Category> level2Categories = allCategories.stream()
                .filter(category -> category.getParentId() == 2)
                .collect(Collectors.toList());

        List<Category> level3Categories = allCategories.stream()
                .filter(category -> category.getParentId() == 3)
                .collect(Collectors.toList());

        level1Categories.forEach(level1Category -> {
            List<Category> tempLevel2Categories = level2Categories.stream()
                    .filter(level2Category -> level2Category.getParentId().equals(level1Category.getId()))
                    .collect(Collectors.toList());
            level1Category.setChildren(tempLevel2Categories);

            tempLevel2Categories.forEach(level2Category -> {
                List<Category> tempLevel3Categories = level3Categories.stream()
                        .filter(level3Category -> level3Category.getParentId().equals(level2Category.getId()))
                        .collect(Collectors.toList());

                level2Category.setChildren(tempLevel3Categories);
            });
        });
        return level1Categories;
    }
}
